/**
 * 批改控制器
 * 处理作文批改相关的HTTP请求
 */

import * as essayService from '../services/essayService.js';
import * as correctionService from '../services/correctionService.js';
import { parseCorrection } from '../utils/resultParser.js';
import { AppError } from '../utils/appError.js';
import { Essay } from '../models/index.js';

/**
 * 提交作文批改
 * POST /api/v1/corrections/:essayId
 * 
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 * @param {Function} next - Express下一个中间件
 */
export const correctEssay = async (req, res, next) => {
  const startTime = Date.now();
  let essay = null;

  try {
    const { essayId } = req.params;
    const userId = req.user.id;

    console.log(`[批改请求] 用户${userId}请求批改作文${essayId}`);

    // 1. 获取作文信息
    const essayResult = await essayService.getEssayById(essayId);
    
    if (!essayResult.success) {
      throw new AppError('NOT_FOUND', '作文不存在', 404);
    }

    essay = essayResult.data;

    // 2. 验证用户权限
    if (essay.userId !== userId) {
      throw new AppError('FORBIDDEN', '无权批改此作文', 403);
    }

    // 3. 检查作文状态是否可以批改
    if (essay.status === 'processing') {
      throw new AppError('CONFLICT', '作文正在批改中，请稍候', 409);
    }

    if (essay.status === 'completed') {
      // 如果已经批改完成，直接返回现有结果
      console.log(`[批改请求] 作文${essayId}已批改完成，返回现有结果`);
      
      return res.status(200).json({
        success: true,
        data: {
          essayId: essay.id,
          status: essay.status,
          score: essay.score,
          correctionResult: essay.correctionResult,
          correctedAt: essay.updatedAt,
        },
        message: '作文已批改完成',
        processingTime: `${(Date.now() - startTime) / 1000}s`,
      });
    }

    // 4. 更新作文状态为批改中
    await essayService.updateEssay(essayId, userId, { status: 'processing' });
    console.log(`[批改流程] 作文${essayId}状态已更新为processing`);

    try {
      // 5. 调用AI批改服务
      console.log(`[批改流程] 开始调用AI批改服务 - 学段: ${essay.gradeLevel}`);
      
      const correctionResult = await correctionService.correctEssay(
        essay.content,
        essay.gradeLevel,
        {
          title: essay.title || '无标题',
        }
      );

      if (!correctionResult.success) {
        throw new AppError(
          'AI_CORRECTION_FAILED',
          `AI批改失败: ${correctionResult.message || '未知错误'}`,
          500
        );
      }

      console.log(`[批改流程] AI批改完成`);

      // 6. 解析批改结果
      const parsedResult = parseCorrection(correctionResult.data, essay.gradeLevel);

      if (!parsedResult.success) {
        console.warn(`[批改流程] 批改结果解析失败，使用默认结构`, parsedResult.error);
      }

      const finalResult = parsedResult.data;
      const finalScore = finalResult.final_score || finalResult.score_breakdown?.total_score || 0;

      console.log(`[批改流程] 最终得分: ${finalScore}`);

      // 7. 更新作文状态和批改结果
      const updateResult = await essayService.updateEssay(essayId, userId, {
        status: 'completed',
        score: finalScore,
        correctionResult: finalResult,
      });

      console.log(`[批改流程] 作文${essayId}批改结果已保存`);

      // 8. 返回批改结果
      const processingTime = `${(Date.now() - startTime) / 1000}s`;
      
      res.status(200).json({
        success: true,
        data: {
          essayId: essay.id,
          status: 'completed',
          score: finalScore,
          correctionResult: finalResult,
          correctedAt: new Date().toISOString(),
          processingTime,
        },
        message: '作文批改完成',
      });

      console.log(`[批改请求] 作文${essayId}批改完成 - 耗时: ${processingTime}`);

    } catch (correctionError) {
      // AI批改或解析失败，更新作文状态为failed
      console.error(`[批改流程] 批改失败:`, correctionError);

      await essayService.updateEssay(essayId, userId, { status: 'failed' });

      throw correctionError;
    }

  } catch (error) {
    // 统一错误处理
    console.error(`[批改请求] 错误:`, {
      message: error.message,
      type: error.type || error.name,
      essayId: req.params.essayId,
      userId: req.user?.id,
    });

    next(error);
  }
};

/**
 * 获取批改结果
 * GET /api/v1/corrections/:essayId
 * 
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 * @param {Function} next - Express下一个中间件
 */
export const getCorrectionResult = async (req, res, next) => {
  try {
    const { essayId } = req.params;
    const userId = req.user.id;

    console.log(`[查询批改结果] 用户${userId}查询作文${essayId}的批改结果`);

    // 1. 获取作文信息
    const essayResult = await essayService.getEssayById(essayId);
    
    if (!essayResult.success) {
      throw new AppError('NOT_FOUND', '作文不存在', 404);
    }

    const essay = essayResult.data;

    // 2. 验证用户权限
    if (essay.userId !== userId) {
      throw new AppError('FORBIDDEN', '无权查看此作文的批改结果', 403);
    }

    // 3. 检查是否有批改结果
    if (essay.status === 'pending') {
      throw new AppError('NOT_FOUND', '作文尚未批改', 404);
    }

    if (essay.status === 'processing') {
      return res.status(200).json({
        success: true,
        data: {
          essayId: essay.id,
          status: 'processing',
          message: '作文正在批改中，请稍候',
        },
      });
    }

    if (essay.status === 'failed') {
      return res.status(200).json({
        success: true,
        data: {
          essayId: essay.id,
          status: 'failed',
          message: '作文批改失败，请重新提交',
        },
      });
    }

    // 4. 返回批改结果
    res.status(200).json({
      success: true,
      data: {
        essayId: essay.id,
        status: essay.status,
        score: essay.score,
        correctionResult: essay.correctionResult,
        correctedAt: essay.updatedAt,
      },
      message: '获取批改结果成功',
    });

  } catch (error) {
    console.error(`[查询批改结果] 错误:`, {
      message: error.message,
      type: error.type || error.name,
      essayId: req.params.essayId,
      userId: req.user?.id,
    });

    next(error);
  }
};

/**
 * 获取批改历史列表
 * GET /api/v1/corrections
 * 
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 * @param {Function} next - Express下一个中间件
 */
export const getCorrectionHistory = async (req, res, next) => {
  try {
    const userId = req.user.id;
    const { limit, offset, gradeLevel, startDate, endDate } = req.query;

    console.log(`[批改历史查询] 用户${userId}查询批改历史`, { limit, offset, gradeLevel, startDate, endDate });

    // 构建过滤条件
    const filters = {
      status: 'completed', // 只返回已完成批改的作文
      limit: limit ? parseInt(limit) : 10,
      offset: offset ? parseInt(offset) : 0,
    };

    // 添加学段过滤
    if (gradeLevel) {
      if (!['primary', 'middle', 'high'].includes(gradeLevel)) {
        throw new AppError('INVALID_INPUT', '学段必须是primary、middle或high之一', 400);
      }
      filters.gradeLevel = gradeLevel;
    }

    // 添加日期范围过滤
    if (startDate || endDate) {
      filters.dateRange = {};
      if (startDate) {
        const start = new Date(startDate);
        if (isNaN(start.getTime())) {
          throw new AppError('INVALID_INPUT', '起始日期格式不正确', 400);
        }
        filters.dateRange.start = start;
      }
      if (endDate) {
        const end = new Date(endDate);
        if (isNaN(end.getTime())) {
          throw new AppError('INVALID_INPUT', '结束日期格式不正确', 400);
        }
        filters.dateRange.end = end;
      }
    }

    // 获取用户的已批改作文列表
    const result = await essayService.getUserEssays(userId, filters);

    if (!result.success) {
      throw new AppError('QUERY_FAILED', result.message || '查询批改历史失败', 500);
    }

    // 格式化响应，只返回批改相关信息
    const corrections = result.data.essays.map((essay) => ({
      essayId: essay.id,
      title: essay.title,
      gradeLevel: essay.gradeLevel,
      score: essay.score,
      status: essay.status,
      correctedAt: essay.updatedAt,
      // 可选：包含完整批改结果（可能导致响应较大）
      // correctionResult: essay.correctionResult,
      // 或者只包含摘要信息
      summary: essay.correctionResult ? {
        totalScore: essay.correctionResult.score_breakdown?.total_score || essay.score,
        errorCount: essay.correctionResult.corrections?.length || 0,
      } : null,
    }));

    res.status(200).json({
      success: true,
      data: {
        corrections,
        pagination: {
          total: result.data.total,
          limit: filters.limit,
          offset: filters.offset,
          hasMore: result.data.hasMore,
        },
      },
      message: '获取批改历史成功',
    });

    console.log(`[批改历史查询] 返回${corrections.length}条记录，共${result.data.total}条`);

  } catch (error) {
    console.error(`[批改历史查询] 错误:`, {
      message: error.message,
      type: error.type || error.name,
      userId: req.user?.id,
    });

    next(error);
  }
};

export default {
  correctEssay,
  getCorrectionResult,
  getCorrectionHistory,
};

